<template>
  <div>
    <!-- 打印预览对话框 -->
    <Modal
      v-model:open="visible"
      title="打印预览"
      width="800px"
      :footer="null"
      @cancel="handleCancel"
    >
      <div class="max-h-[70vh] overflow-y-auto pb-16">
        <!-- 打印内容区域 -->
        <div id="printContent" class="p-5 bg-white min-h-[calc(100vh-200px)] flex flex-col">
          <div class="w-full mx-auto font-sans text-base leading-7 text-black flex-1 flex flex-col">
            <!-- 标题 -->
            <div class="text-center mb-5">
              <h2 class="text-2xl font-bold m-0">车辆采购费用单</h2>
            </div>
            
            <!-- 基本信息 -->
            <div class="mb-2">
              <div class="flex justify-between mb-4">
                <div class="flex items-center">
                  <span class="font-normal mr-1.5">公司：</span>
                  <span class="min-w-[100px]">{{ printData.companyName }}</span>
                </div>
                <div class="flex items-center ml-auto">
                  <span class="font-normal mr-1.5">日期：</span>
                  <span class="min-w-[100px]">{{ formatDate(printData.approveTime) }}</span>
                </div>
              </div>
              <div class="flex justify-between mb-4">
                <div class="flex items-center">
                  <span class="font-normal mr-1.5">采购合同号：</span>
                  <span class="min-w-[100px]">{{ printData.contractNo }}</span>
                </div>
                <div class="flex items-center ml-auto">
                  <span class="font-normal mr-1.5">供应商：</span>
                  <span class="min-w-[100px]">{{ printData.supplierName }}</span>
                </div>
              </div>
            </div>
            
            <!-- 车辆明细表格 -->
            <div class="mb-2">
              <table class="w-full border-collapse border border-black">
                <thead>
                  <tr>
                    <th class="border border-black p-3 text-center bg-gray-100 font-bold w-[60px] text-base">序号</th>
                    <th class="border border-black p-3 text-center bg-gray-100 font-bold w-[120px] text-base">车型</th>
                    <th class="border border-black p-3 text-center bg-gray-100 font-bold w-[100px] text-base">车架号</th>
                    <th class="border border-black p-3 text-center bg-gray-100 font-bold w-[80px] text-base">备注</th>
                    <th class="border border-black p-3 text-center bg-gray-100 font-bold w-[100px] text-base">金额</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in printData.details" :key="index">
                    <td class="border border-black p-3 text-center text-base">{{ index + 1 }}</td>
                    <td class="border border-black p-3 text-center text-base">{{ getSpuName(item) }}</td>
                    <td class="border border-black p-3 text-center text-base">{{ item.order?.frameNo || '' }}</td>
                    <td class="border border-black p-3 text-center text-base">{{ getCarSpecs(item.order) }}</td>
                    <td class="border border-black p-3 text-center text-base">{{ formatAmount(item.purchaseAmount) }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- 合计信息 -->
            <div class="mb-5">
              <div class="flex items-center mb-2.5">
                <span class="font-normal mr-2.5">金额合计：</span>
                <span class="border-b border-black pb-0.5 mr-5">{{ formatAmount(printData.totalAmount) }}元</span>
                <span class="font-normal mr-2.5 ml-5">金额大写：</span>
                <span class="border-b border-black pb-0.5 flex-1">{{ convertToChinese(printData.totalAmount) }}</span>
              </div>
            </div>
            
            <!-- 备注 -->
            <div class="mb-7.5">
              <div class="font-normal mb-2.5">备注：</div>
              <div class="border border-black p-3 min-h-[100px] leading-relaxed text-base">
                {{ printData.remark || '' }}
              </div>
            </div>
            
            <!-- 签名区域 - 固定在底部 -->
            <div class="pt-2 pb-4">
              <div class="flex justify-between">
                <div class="flex items-center">
                  <span class="font-normal mr-2.5">申请人：</span>
                  <span class="border-b border-black min-w-[100px] pb-1 text-center">{{ printData.applicantName }}</span>
                </div>
                <div class="flex items-center">
                  <span class="font-normal mr-2.5">审核人：</span>
                  <span class="border-b border-black min-w-[100px] pb-1 text-center">{{ printData.approverName }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 固定在底部的按钮区域 -->
      <div class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 flex justify-center gap-3 z-10">
        <Button type="primary" @click="handlePrint">打印</Button>
        <Button @click="handleCancel">取消</Button>
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { Modal, Button, Space } from 'ant-design-vue';
import printJS from 'print-js';
import html2canvas from 'html2canvas';
import dayjs from 'dayjs';
import nzhcn from 'nzh/cn';
import type { PurchaseContractVO } from '#/api/trade/purchaseContract/model';
import { spuInfo } from '#/api/trade/spu';

const visible = ref(false);
const printData = ref<any>({});

// 格式化日期
const formatDate = (date?: string | Date) => {
  if (!date) return dayjs().format('YYYY年MM月DD日');
  return dayjs(date).format('YYYY年MM月DD日');
};

// 格式化金额
const formatAmount = (amount?: number | string) => {
  if (!amount) return '0';
  return Number(amount).toString();
};

// 数字转中文大写 - 使用nzh包
const convertToChinese = (amount?: number | string) => {
  const num = Number(amount);
  // 使用nzh包转换为中文大写
  return nzhcn.encodeB(num) + '圆';
};

// 获取车辆规格信息
const getCarSpecs = (order?: any) => {
  if (!order) return '';
  return order.saleContract.details[0].others
};

// SPU名称缓存
const spuNameCache = ref<Record<string, string>>({});

// 预加载所有SPU名称
const loadSpuNames = async () => {
  if (!printData.value?.details) return;
  
  const spuIds = new Set<string>();
  
  // 收集所有需要的spuId
  printData.value.details.forEach((item: any) => {
    const detail = item?.order?.saleContract?.details?.[0];
    if (detail?.spuId && !detail.spuName) {
      spuIds.add(detail.spuId);
    }
  });
  
  // 并发获取所有SPU信息
  const promises = Array.from(spuIds).map(async (spuId) => {
    if (spuNameCache.value[spuId]) return;
    
    try {
      const response = await spuInfo(spuId);
      spuNameCache.value[spuId] = response.spuName || spuId;
    } catch (error) {
      console.error(`获取SPU信息失败 (${spuId}):`, error);
      spuNameCache.value[spuId] = spuId;
    }
  });
  
  await Promise.all(promises);
};

// 获取SPU名称（同步版本）
const getSpuName = (item?: any) => {
  if (!item?.order?.saleContract?.details?.[0]) return '';
  const detail = item.order.saleContract.details[0];
  
  // 如果已经有spuName，直接返回
  if (detail.spuName) return detail.spuName;
  
  const spuId = detail.spuId;
  if (!spuId) return '';
  
  // 从缓存中获取
  return spuNameCache.value[spuId] || spuId;
};

// 打开打印预览
const open = async (data?: any) => {
  if (data) {
    printData.value = data;
    // 预加载SPU名称
    await loadSpuNames();
  }
  visible.value = true;
};

// 关闭对话框
const handleCancel = () => {
  visible.value = false;
};

// 执行打印 - 使用html2canvas转换为图像打印
const handlePrint = async () => {
  const htmlContent = document.getElementById('printContent') as HTMLElement;
  try {
    // 高解像度でキャンバスを生成（表示効果と一致させるため）
    const canvas = await html2canvas(htmlContent, {
      scale: 3, // 高解像度で生成
      useCORS: true,
      allowTaint: true,
      backgroundColor: '#ffffff',
      width: htmlContent.scrollWidth,
      height: htmlContent.scrollHeight,
    });

    // キャンバスをBase64画像に変換
    const imgData = canvas.toDataURL('image/png');

    // print-jsを使用して画像を印刷
    printJS({
      printable: imgData,
      type: 'image',
      imageStyle: 'width:100%;margin:0;padding:0;',
      style: '@page { margin: 0; }',
      onPrintDialogClose: () => {
        console.log('打印对话框已关闭');
      },
    });
  } catch (error) {
    console.error('打印失败:', error);
  }
};

// 暴露方法给父组件
defineExpose({
  open,
});
</script>

<style scoped>
/* 打印样式 */
@media print {
  .fixed {
    display: none !important;
  }
}
</style>
